<template>
  <div class="collection">
    <div>
      <a-card :bordered="false" style="border-radius:8px;margin-top:10px">
        <div class="card_title">
          提交收款 店铺：{{ shopname }}
        </div>
        <a-table
          :columns="columns"
          :rowKey="activity => activity.pd_id"
          :dataSource="activity"
          :loading="loading"
          @change="handleTableChange"
          :pagination="false"
        >
          <div slot="pd_subTitle" slot-scope="text, row">
            <div class="flex row_bet col_center" style="width: 288px;margin: 0 auto;">
              <img :src="row.pd_goodsImgUrl" alt="" class="br4" style="width: 60px;height: 60px;">
              <div style="font-size: 13px;text-align: left;margin-left: 18px;">
                <div class="line-1" style="margin-bottom: 5px;">
                  <a :href="'https://detail.tmall.com/item.htm?id='+row.pd_itemId" target="_blank">{{ row.pd_subTitle
                  }}</a></div>
                <div style="margin-bottom: 4px;">商品ID：{{ row.pd_itemId }}</div>
                <div class="line-1" style="width: 210px;">备注：{{ row.pd_mark }}</div>
              </div>
            </div>
          </div>
          <div slot="pd_couponUrl" slot-scope="text, row">
            <div style="font-size: 13px;width:158px;margin: 0 auto;">
              <div>券名称：{{ row.pd_couponName }}</div>
              <div>止：{{ row.pd_couponEndTime }}</div>
            </div>
          </div>
          <div slot="img" slot-scope="text, row,index">
            <div class="showimg" v-if="row.img===null">
              <a-upload
                name="file"
                action="https://app.letuilm.com/api/upload"
                list-type="picture-card"
                :multiple="false"
                :show-upload-list="false"
                :before-upload="beforeUpload"
                @change="
                  (file) => {
                    handleChange2(
                      file,
                      index
                    );
                  }">
                <div class="nogoodsimg br4">
                  <div>
                    <a-icon type="plus" style="font-size: 17px;margin-top: 11px"/>
                  </div>
                  <div style="color: rgba(0,0,0,0.65);font-size: 14px;">
                    上传照片
                  </div>
                </div>
              </a-upload>
            </div>
            <img v-else :src="row.img" alt="" style="width: 70px;height: 60px;">
          </div>
          <div slot="payNum" slot-scope="text, row, index">
            <div>
              <a-input
                placeholder="点击填写"
                v-model="row.payNum"
                style="width: 85px;border: 0;"
                @change="iptchange(index)"/>
            </div>
          </div>
          <div slot="pd_selmType" slot-scope="text, row">
            <div> {{ parseInt(row.pd_selmType) === 3 ? row.pd_serviceRate :
              (Number(row.pd_goodsCouponPrice)*(Number(row.pd_serviceRate)/100)).toFixed(2) }}
            </div>
          </div>
          <div slot="clearorder" slot-scope="text, row">
            <div>{{ parseInt(row.pd_selmType) === 1 ? '支付金额/结算券后价*服务费' :
              parseInt(row.pd_selmType) === 2?'支付金额*服务费率' :'累计使用张数或件数*服务费单价' }}
            </div>
          </div>
          <!--          <div slot="selmNum" slot-scope="row">-->
          <!--          </div>-->
          <div slot="active" slot-scope="row">
            <a-popconfirm placement="left" ok-text="确认" cancel-text="取消" @confirm="dodel(row)">
              <template slot="title">
                确认删除吗?
              </template>
              <a-button type="link" style="color: red;">删除</a-button>
            </a-popconfirm>
          </div>
        </a-table>
        <div class="total">
          该组共结算商品 <span class="tfont">{{ activity.length }}</span> 件，应收金额 <span class="tfont">￥{{ allprice | numFormat }}元</span>
        </div>
        <a-divider/>
        <div class="submitinfo">
          <div class="formpart flex row_left col_top">
            <span class="title">转账截图</span>
            <div class="uploadimg">
              <a-upload
                name="file"
                action="https://app.letuilm.com/api/upload"
                list-type="picture-card"
                :file-list="fileList2"
                :multiple="false"
                :before-upload="beforeUpload"
                @preview="handlePreview"
                @change="handleChange">
                <div v-if="fileList2.length < 1">
                  <div class="nogoodsimg br4">
                    <div>
                      <a-icon type="plus" style="font-size: 24px;margin-top: 24px"/>
                    </div>
                    <div style="color: rgba(0,0,0,0.65);font-size: 14px;">
                      上传照片
                    </div>
                  </div>
                </div>
              </a-upload>
              <div>只可上传一张</div>
            </div>
          </div>
          <div class="formpart flex row_left col_top">
            <span class="title">异常截图</span>
            <div class="uploadimg">
              <a-upload
                name="file"
                action="https://app.letuilm.com/api/upload"
                list-type="picture-card"
                :file-list="fileList"
                :multiple="false"
                :before-upload="beforeUpload"
                @preview="handlePreview"
                @change="handleChange3">
                <div v-if="fileList.length < 5">
                  <div class="nogoodsimg br4">
                    <div>
                      <a-icon type="plus" style="font-size: 24px;margin-top: 24px"/>
                    </div>
                    <div style="color: rgba(0,0,0,0.65);font-size: 14px;">
                      上传照片
                    </div>
                  </div>
                </div>
              </a-upload>
              <div>可上传五张</div>
            </div>
          </div>
          <div class="formpart flex row_left col_top">
            <span class="title">商家打款时间</span>
            <div class="antibr4">
              <a-date-picker
                format="YYYY-MM-DD HH:mm:ss"
                @change="timeChange"
                :show-time="{ format: 'HH:mm:ss' }"
                style="width: 224px;height: 30px;border-radius: 4px;"
              />
            </div>
          </div>
          <div class="formpart flex row_left col_top">
            <span class="title">实收金额</span>
            <div class="antibr4">
              <a-input suffix="元" style="width: 126px;" v-model="form.gf_actualPay"/>
            </div>
          </div>
          <div class="formpart flex row_left col_top">
            <span class="title">收款账号</span>
            <div class="antibr4">
              <a-input placeholder="填写你的收款账号" style="width: 224px;" v-model="form.gf_actualUser"/>
            </div>
          </div>
          <div class="formpart flex row_left col_top">
            <span class="title">备注</span>
            <div class="antibr4">
              <a-textarea placeholder="审核人员能看到你的备注" :rows="3" style="width: 556px;" allow-clear v-model="form.gf_mark"/>
            </div>
          </div>
          <div class="formpart flex row_left col_top">
            <span class="title"></span>
            <a-button type="primary" class="br4" style="width: 224px;height: 30px;" @click="dosubmit">
              提交审核
            </a-button>
          </div>
        </div>
      </a-card>
    </div>
    <a-modal v-model="previewVisible" :footer="null" @cancel="handleCancel">
      <img style="width: 100%" :src="previewImage"/>
    </a-modal>
  </div>
</template>

<script>
  import { dosubmitpay, getshoporder } from '@/api/collectionApi'
  import moment from 'moment'

  function getBase64 (file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = error => reject(error)
    })
  }

  export default {
    name: 'Collection',
    data () {
      return {
        moment,
        previewVisible: false,
        previewImage: '',
        shopname: '',
        allprice: 0.00,
        columns: [
          {
            title: '商品信息',
            dataIndex: 'pd_subTitle',
            align: 'center',
            scopedSlots: {
              customRender: 'pd_subTitle'
            }
          },
          {
            title: '优惠券',
            dataIndex: 'pd_couponUrl',
            align: 'center',
            scopedSlots: {
              customRender: 'pd_couponUrl'
            }
          },
          {
            title: '支付金额截图',
            dataIndex: 'img',
            align: 'center',
            scopedSlots: {
              customRender: 'img'
            }
          },
          {
            title: '支付金额/件数',
            align: 'center',
            scopedSlots: {
              customRender: 'payNum'
            }
          },
          {
            title: '结算券后价',
            dataIndex: 'pd_goodsCouponPrice',
            align: 'center',
            scopedSlots: {
              customRender: 'pd_goodsCouponPrice'
            }
          },
          {
            title: '服务费单价',
            dataIndex: 'pd_selmType',
            align: 'center',
            scopedSlots: {
              customRender: 'pd_selmType'
            }
          },
          {
            title: '结算方式',
            align: 'center',
            scopedSlots: {
              customRender: 'clearorder'
            }
          },
          {
            title: '结算金额',
            dataIndex: 'selmNum',
            align: 'center',
            scopedSlots: {
              customRender: 'selmNum'
            }
          },
          {
            title: '操作',
            align: 'center',
            scopedSlots: {
              customRender: 'active'
            }
          }
        ],
        activity: [
          // {
          //   pd_activityType: 1,
          //   pd_addTime: '2020-08-24 15:09:20',
          //   pd_cateText: '美妆护肤',
          //   pd_circleText: null,
          //   pd_commissionRate: '40',
          //   pd_couponActivityId: 'd5cfc53ac27345a48557a05fbb75aa7c',
          //   pd_couponEndTime: '2020-08-30 23:59:59',
          //   pd_couponMoney: '10.00',
          //   pd_couponName: '陌陌',
          //   pd_couponNum: 100000,
          //   pd_couponSingle: '29.00',
          //   pd_couponStartTime: '2020-08-25 00:00:00',
          //   pd_couponSurplus: 100000,
          //   pd_couponUrl: 'https://uland.taobao.com/quan/detail?sellerId=2454384653&activityId=d5cfc53ac27345a48557a05fbb75aa7c',
          //   // pd_detailArr: "{"sellCount":"9500+","categoryId":"50010797","shopType":"B","shopId":"118233543","userId":"2454384653","shopName":"依莱丽旗舰店","shopIcon":"//img.alicdn.com/imgextra//fe/a1/TB1D7WLaRfM8KJjSZFhSuwRyFXa.jpg","sellerNick":"依莱丽旗舰店","title":"依莱丽眼线笔不晕染防水防汗持久不易脱色硬头棕色初学者眼线液笔","rootCategoryId":"50010788"}"
          //   pd_dtkId: 31829554,
          //   pd_dtkState: 1,
          //   pd_dtkText: '',
          //   pd_dtkUserId: 1,
          //   pd_dtk_reason: null,
          //   pd_error_status: 0,
          //   pd_error_user: 0,
          //   pd_finaState: 0,
          //   pd_goodsCouponPrice: '19.00',
          //   pd_goodsImgUrl: 'https://img.alicdn.com/imgextra/i3/2454384653/O1CN01huMPPE1kF7VOMdF4c_!!2454384653.jpg',
          //   pd_goodsPrice: '29.00',
          //   pd_hdkId: 9444237,
          //   pd_hdkState: 1,
          //   pd_hdkText: '',
          //   pd_id: 160402,
          //   pd_issue_num: 0,
          //   pd_issue_service_fee: '0.00',
          //   pd_itemId: '550035640725',
          //   pd_manaUser: '跑单四',
          //   pd_mana_at: 0,
          //   pd_mana_mark: null,
          //   pd_mark: '团长  明天预告/明天提交大淘客8.24 08/03',
          //   pd_pure_url: '',
          //   pd_realUrl: '[]',
          //   pd_sellCount: 9500,
          //   pd_selmType: 1,
          //   pd_serviceRate: '0.6',
          //   pd_shoudan: 0,
          //   pd_shzId: 4711634,
          //   pd_shzState: 1,
          //   pd_shzText: '',
          //   pd_subTitle: '【第二件1元】魅眼速干防水眼线笔',
          //   pd_superUrl: '/public/static/upload/img/20200824/e22efb3065a9efc7c79e6e009f18e6e3.jpg',
          //   pd_userId: 197,
          //   pd_videoUrl: '',
          //   pd_withdraw: 0,
          //   pd_writing: '【第2件1元】拍2支！拍2支！！【流汗游泳，就是不晕染】单品爆卖117万支，屈臣氏热卖大牌，抖音爆款，深邃大眼一笔成型，防水防油，持久不晕染，3秒速干，5秒温水可卸，敲好用！【赠运费险】'
          // }
        ],
        loading: false,
        form: {
          gf_activityId: '', // 优惠卷id
          gf_goodsData: '', // 商品信息
          gf_sellerPayTime: '', // 支付时间 例如 2020-02-08 22:32:12
          gf_accountsPic: '', // 转账截图
          gf_actualPay: '', // 转账金额
          gf_actualUser: '', // 收款账号
          gf_mark: '', // 备注
          gf_errorImg: [] // 异常图片 有就传 没就传 []
        },
        fileList: [
          // {
          //   uid: '-1',
          //   name: 'image.png',
          //   status: 'done',
          //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
          // }
        ],
        fileList2: [
          // {
          //   uid: '-1',
          //   name: 'image.png',
          //   status: 'done',
          //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
          // }
        ],
        pagination: {
          pageSize: 15,
          page: 1
        },
        endtime: null
      }
    },
    computed: {
      issue: function () {
        return this.$store.getters.issue
      }
    },
    filters: {
      numFormat (input) {
        return input && input.toString()
          .replace(/(^|\s)\d+/g, (m) => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
      }
    },
    destroyed () {
      this.$store.dispatch('setIssuename', '')
    },
    created () {
      // console.log('issue', this.issue)
      if (this.issue.gf_activityId) {
        this.form.gf_activityId = this.issue.gf_activityId
        this.getshoporder(this.issue.gf_activityId)
      }
      if (this.issue.pd_couponActivityId) {
        this.shopname = this.issue.si_shopName
        this.form.gf_activityId = this.issue.pd_couponActivityId
        this.getshoporder(this.issue.pd_couponActivityId)
      }
    },
    mounted () {
    },
    methods: {
      dosubmit () {
        if (this.fileList2.length > 0) {
          this.form.gf_accountsPic = '//' + this.fileList2[0].response.data.url
        }
        if (this.fileList.length > 0) {
          for (const i in this.fileList) {
            var obj2 = {}
            obj2.goodsId = '//' + this.fileList[i].response.data.url
            this.form.gf_errorImg.push(obj2)
          }
          this.form.gf_errorImg = JSON.stringify(this.form.gf_errorImg)
        }
        var arr = []
        for (const j in this.activity) {
          var obj = {}
          obj.goodsId = this.activity[j].pd_itemId
          obj.img = this.activity[j].img
          obj.payNum = this.activity[j].payNum
          obj.selmNum = this.activity[j].selmNum
          arr.push(obj)
        }
        this.form.gf_goodsData = JSON.stringify(arr)
        // console.log('form', this.form)
        if (this.form.gf_accountsPic !== '' &&
          this.form.gf_activityId !== '' &&
          this.form.gf_actualPay !== '' &&
          this.form.gf_actualUser !== '' &&
          this.form.gf_errorImg !== '' &&
          this.form.gf_goodsData !== '' &&
          this.form.gf_mark !== '' &&
          this.form.gf_sellerPayTime !== ''
        ) {
          dosubmitpay(this.form).then(res => {
            // console.log(res)
            if (res.code === 200) {
              this.$message.success('提交成功!')
            }
          }).catch(err => {
            console.log(err)
          })
        } else {
          this.$message.info('请检查所需条件!')
        }
      },
      iptchange (index) {
        const payNum = Number(this.activity[index].payNum) // 支付金额
        const goodsCouponPrice = Number(this.activity[index].pd_goodsCouponPrice) // 券后价
        const serviceRate = Number(this.activity[index].pd_serviceRate) // 服务费率
        if (this.activity[index].pd_selmType === 1) {
          this.activity[index].selmNum = (payNum / goodsCouponPrice * (goodsCouponPrice * serviceRate / 100)).toFixed(2)
        } else if (this.activity[index].pd_selmType === 2) {
          this.activity[index].selmNum = (payNum * serviceRate / 100).toFixed(2)
        } else {
          this.activity[index].selmNum = (payNum * serviceRate).toFixed(2)
        }
        this.allprice = 0
        for (let i = 0; i < this.activity.length; i++) {
          if (this.activity[i].selmNum !== '-') {
            this.allprice += Number(this.activity[i].selmNum)
          }
        }
      },
      handleCancel () {
        this.previewVisible = false
      },
      async handlePreview (file) {
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj)
        }
        this.previewImage = file.url || file.preview
        this.previewVisible = true
      },
      handleChange3 ({ fileList }) {
        this.fileList = fileList
        // console.log(this.fileList)
        if (this.fileList[0].response) {
          // console.log(this.fileList[0].response.data.url)
        }
      },
      handleChange ({ fileList }) {
        this.fileList2 = fileList
        if (this.fileList2[0].response) {
          console.log(this.fileList2[0].response.data.url)
        }
      },
      handleChange2 (info, index) {
        // console.log('info', info, index)
        if (info.file.response) {
          this.activity[index].img = '//' + info.file.response.data.url
          // this.form.pro_img = '//' + info.file.response.data.url
        }
      },
      beforeUpload (file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJpgOrPng) {
          this.$message.error('对不起,只支持jpg/png格式的图片!')
        }
        const isLt2M = file.size / 1024 / 1024 < 5
        if (!isLt2M) {
          this.$message.error('对不起!图片大小超过5M!')
        }
        return isJpgOrPng && isLt2M
      },
      dodel (row) {
        // console.log(row)
        for (let i = 0; i < this.activity.length; i++) {
          if (this.activity[i].pd_id === row.pd_id) {
            this.activity.splice(i, 1)
            this.$message.success('删除成功!')
            return
          }
        }
      },
      getshoporder (id) {
        this.loading = true
        getshoporder({
          activityId: id
        })
          .then(res => {
            // console.log(res)
            const arr = res.data
            for (let i = 0; i < arr.length; i++) {
              arr[i].img = null
              arr[i].payNum = ''
              arr[i].selmNum = '-'
            }
            this.activity = arr
            this.shopname = JSON.parse(this.activity[0].pd_detailArr).shopName
            // console.log(arr)
            //  this.count = res.data.count
            // const pagination = {
            //   ...this.pagination
            // }
            // pagination.total = res.data.count
            // this.pagination = pagination
            this.loading = false
          })
          .catch(err => {
            console.log(err)
          })
      },
      handleTableChange (pagination, filters) {
        // console.log(pagination)
        const pager = {
          ...this.pagination
        }
        pager.current = pagination.current
        this.pagination = pager
        this.fetch({
          results: pagination.pageSize,
          page: pagination.current,
          ...filters
        })
      },
      fetch (params = {}) {
        // console.log('params:', params)
        this.loading = true
        this.getshoporder(params.page, 15, 2, this.status, this.search)
      },
      timeChange (date, dateString) {
        // console.log(date, dateString)
        this.form.gf_sellerPayTime = dateString
      },
      /*
      * 获取传入对象数组里的某个属性和传入的属性的值等于传入的值
      * 数组对象 对象的的某个属性 属性应该对应的值
      * return list 返回数组对象的符合条件的一项
      * */
      getobjnature (list, key, nature) {
        for (const i in list) {
          if (list[i][key] === nature) {
            return list[i]
          }
        }
        return null
      }
    }
  }
</script>
<style lang="less" scoped>
  .collection {
    .card_title {
      color: rgba(16, 16, 16, 100);
      font-size: 14px;
      margin-bottom: 19px;
      font-weight: 600;
    }

    .groupbox {
      /deep/ .ant-input {
        border-radius: 4px;
      }
    }

    .a_blue {
      color: #00A0E9;
      cursor: pointer;
    }

    .showimg {
      /deep/ .ant-upload {
        width: 56px;
        height: 20px;
        padding: 0px;
        margin: 0;
        border: none;
        background-color: transparent;
      }

      .nogoodsimg {
        width: 70px;
        height: 60px;
        background-color: rgba(0, 0, 0, 0.02);
      }
    }

    .uploadimg {
      /deep/ .ant-upload {
        width: 56px;
        height: 20px;
        padding: 0px;
        margin: 0;
        border: none;
        background-color: transparent;
      }

      /deep/ .ant-upload-picture-card-wrapper {
        display: flex;
      }

      .nogoodsimg {
        width: 104px;
        height: 104px;
        background-color: rgba(0, 0, 0, 0.02);
      }
    }

    .total {
      font-size: 14px;
      margin-top: 26px;
      margin-bottom: 4px;
      float: right;

      .tfont {
        font-size: 16px;
        color: #333333;
        font-weight: 600;
      }
    }

    .submitinfo {
      .formpart {
        margin-bottom: 24px;

        .title {
          margin-right: 31px;
          width: 88px;
          text-align: right
        }

        .antibr4 {
          /deep/ .ant-input {
            border-radius: 4px;
          }
        }
      }
    }
  }
</style>
